package lee.study.StackAndQueue;

import java.util.Stack;

public class MinStack {
    //属性
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {//构造方法
        this.stack = new Stack<>();
        this.minStack = new Stack<>();
    }

    public void push(int x) {//放入元素
        stack.push(x);
        if (minStack.empty()) {//最小栈是否为空，为空则将x放入最小栈
            minStack.push(x);
        } else {
            int top = minStack.peek();//取最小栈顶元素进行比较
            if (x <= top) {
                minStack.push(x);
            }
        }
    }

    public void pop() {//弹出栈顶元素
        if (!stack.empty()) {
            int tmp = stack.pop();//将stack中的栈顶元素记录下来与minStack比较，如果相同，则minStack也需要pop
            if (tmp == minStack.peek()) {
                minStack.pop();
            }
        }
    }

    public int top() {//得到栈顶元素且不删除
        if (stack.empty()) {
            return -1;
        }
        return stack.peek();
    }

    public int getMin(){//获得栈中的最小值
        if (minStack.empty()){
            return -1;
        }
        return minStack.peek();
    }
}
